package com.easemob.chatuidemo.activity;

import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.R;
import com.easemob.chatuidemo.domain.User;
import com.easemob.chatuidemo.service.UserService;
import com.easemob.chatuidemo.utils.FileUtil;
import com.easemob.chatuidemo.utils.FlyAntGlobalVar;
import com.easemob.chatuidemo.utils.JSONUtil;
import com.easemob.chatuidemo.utils.NetUtil;
import com.easemob.chatuidemo.utils.StringUtils;
import com.easemob.chatuidemo.video.util.AsyncTask;
/**
 * 用户界面
 * @author pc
 *
 */
public class UserFragment extends Fragment implements OnClickListener {
    
    /**
     * 用户头像布局
     */
    private ImageView iv_user_head_portrait;
    
    private RelativeLayout rl_user_nickname;
    /**
     * 用户姓名布局
     */
    private RelativeLayout rl_user_name;
    /**
     * 用户手机布局
     */
    private RelativeLayout rl_user_phonenum;
    /**
     * 取货地址布局
     */
    private RelativeLayout rl_user_goodsaddress;
    /**
     * 个人地址布局
     */
    private RelativeLayout rl_user_personaddress;
    /**
     * 设置按钮布局
     */
    private ImageButton btn_user_setting;
    /**
     * 用户姓名/单位
     */
    private TextView tv_user_name;
    /**
     * 昵称
     */
    private TextView tv_user_nickname;
    /**
     * 用户联系方式
     */
    private TextView tv_user_phonenum;
    /**
     * 取货地址
     */
    private TextView tv_user_goodsaddress;
    /**
     * 个人地址
     */
    private TextView tv_user_address;
    
    
    public static final int REQUSET = 1;
    public static final int SELECT_PIC_BY_TACK_PHOTO = 5;
    public static final int SELECT_PIC_BY_PICK_PHOTO = 6;
    ProgressDialog delLoadingDialog = null;
    private static final String TAG = "UserFragment";
    
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE = 13;
    private static final int CAMERA_REQUEST_CODE = 11;
    private static final int RESULT_REQUEST_CODE = 12;
    /*头像名称*/
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    private static final int REQUESTCODE_CUTTING = 14;
    private Context mContext;
    private ProgressDialog pd;
    
    private String resultStr = "";
    private boolean hidden;
    SharedPreferences sp;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) 
            return;
        
        mContext = getActivity();
        
        iv_user_head_portrait = (ImageView) getView().findViewById(R.id.iv_user_head);
        rl_user_name = (RelativeLayout) getView().findViewById(R.id.user_rl_name);
        rl_user_nickname = (RelativeLayout) getView().findViewById(R.id.user_rl_nickname);
        rl_user_phonenum = (RelativeLayout) getView().findViewById(R.id.user_rl_phonenum);
        rl_user_goodsaddress = (RelativeLayout) getView().findViewById(R.id.user_rl_goodsaddress);
        rl_user_personaddress = (RelativeLayout) getView().findViewById(R.id.user_rl_address);
        
        tv_user_name = (TextView) getView().findViewById(R.id.user_tv_name);
        tv_user_nickname = (TextView) getView().findViewById(R.id.user_tv_nickname);
        tv_user_phonenum = (TextView) getView().findViewById(R.id.user_tv_phonenum);
        tv_user_goodsaddress = (TextView) getView().findViewById(R.id.user_tv_goodsaddress);
        tv_user_address = (TextView) getView().findViewById(R.id.user_tv_address);
        
        btn_user_setting = (ImageButton) getView().findViewById(R.id.user_ibtn_setting);
        
        iv_user_head_portrait.setOnClickListener(this);
        rl_user_name.setOnClickListener(this);
        rl_user_nickname.setOnClickListener(this);
        rl_user_phonenum.setOnClickListener(this);
        rl_user_goodsaddress.setOnClickListener(this);
        rl_user_personaddress.setOnClickListener(this);
        btn_user_setting.setOnClickListener(this);
        
//        actionReceiver = new MediaActionReceiver();
        
    }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refresh();
    }

    public void onClick(View view){
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        int index = 99;
        String username = tv_user_name.getText().toString();
        String nickname = tv_user_nickname.getText().toString();
        String sendTel = tv_user_phonenum.getText().toString();
        String goosdaddress = tv_user_goodsaddress.getText().toString();
        String address = tv_user_address.getText().toString();
        intent.setClass(getActivity(), ChangeUserinfoActivity.class);

        switch (view.getId()) {
        case R.id.iv_user_head:
            Toast.makeText(this.getActivity(), "上传头像", Toast.LENGTH_SHORT)
                    .show();
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("选择头像");
            String[] items = {"选择图片","拍摄"};
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case 0:
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // 设置文件类型
                        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intentFromGallery,
                                SELECT_PIC_BY_PICK_PHOTO);

                        break;
                    case 1:
                        Intent intentFromCapture = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // 判断存储卡是否可以用，可用进行存储
                        if (StringUtils.hasSdcard()) {
                            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(new File(Environment
                                            .getExternalStorageDirectory(),
                                            IMAGE_FILE_NAME)));
                        }
                        startActivityForResult(intentFromCapture,
                                SELECT_PIC_BY_TACK_PHOTO);
                        break;
                    default:
                        break;
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
            break;
        case R.id.user_rl_name:
            index = 1;
            bundle.putInt("index", index);
            bundle.putString("information", username);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUSET);
            break;
        case R.id.user_rl_phonenum:
            index = 2;
            bundle.putInt("index", index);
            bundle.putString("information", sendTel);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUSET);
            break;
        case R.id.user_rl_goodsaddress:
            index = 3;
            bundle.putInt("index", index);
            bundle.putString("information", goosdaddress);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUSET);
            break;
        case R.id.user_rl_address:
            index = 4;
            bundle.putInt("index", index);
            bundle.putString("information", address);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUSET);
            break;
        case R.id.user_rl_nickname:
            index = 5;
            bundle.putInt("index", index);
            bundle.putString("information", nickname);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUSET);
            break;
        case R.id.user_ibtn_setting:
            Intent intentlogout = new Intent();
            intentlogout.setClass(getActivity(), SettingActivity.class);
            startActivityForResult(intentlogout, REQUSET);
            break;
        default:
            break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
        case 1:
            tv_user_name.setText(data.getExtras().getString("name"));
            break;
        case 2:
            tv_user_phonenum.setText(data.getExtras().getString("sendTel"));
            break;
        case 3:
            tv_user_goodsaddress.setText(data.getExtras().getString(
                    "sendAddress"));
            break;
        case 4:
            tv_user_address.setText(data.getExtras().getString("address"));
            break;
        case 5:
            tv_user_nickname.setText(data.getExtras().getString("nickname"));
            break;
        case 99:

            break;
        case 999:
            ((MainActivity) getActivity()).finish();
            
            break;
        }
        
        switch (requestCode) {
        case SELECT_PIC_BY_TACK_PHOTO:
            File temp = new File(Environment.getExternalStorageDirectory() +"/" + IMAGE_FILE_NAME);
            startPhotoZoom(Uri.fromFile(temp));
            
            break;
        case SELECT_PIC_BY_PICK_PHOTO:
            startPhotoZoom(data.getData());
            break;
        case REQUESTCODE_CUTTING:
            if (data != null) {
                setPicToView(data);
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }
    
    /**
     * 保存裁剪之后的图片数据
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(null, photo);
            urlpath = FileUtil.saveFile(mContext, "faceImage.jpg", photo);
            iv_user_head_portrait.setImageDrawable(drawable);

            pd = ProgressDialog.show(mContext, null, "正在上传图片，请稍候...");
            
            new Thread(uploadImageRunnable).start();
        }
    }
    private String imgUrl; 
    Runnable uploadImageRunnable = new Runnable() {
        
        @Override
        public void run() {
            imgUrl = "http://www.365jiaju.com/app/im/uploadUpic.ashx?uid=" + FlyAntGlobalVar.uid;
            if(TextUtils.isEmpty(imgUrl)){
                Toast.makeText(mContext, "还没有设置上传服务器的路径！", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i(TAG, imgUrl);
            Map textParams = new HashMap();
            Map fileparams = new HashMap();
            
            
            try {
                URL url = new URL(imgUrl);
                textParams = new HashMap();
                fileparams = new HashMap();
                
                File file = new File(urlpath);
                fileparams.put("image", file);
                // 利用HttpURLConnection对象从网络中获取网页数据
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 设置连接超时（记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作）
                conn.setConnectTimeout(5000);
                // 设置允许输出（发送POST请求必须设置允许输出）
                conn.setDoOutput(true);
                // 设置使用POST的方式发送
                conn.setRequestMethod("POST");
                // 设置不使用缓存（容易出现问题）
                conn.setUseCaches(false);
                conn.setRequestProperty("Charset", "UTF-8");//设置编码   
                // 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头
                conn.setRequestProperty("ser-Agent", "Fiddler");
                // 设置contentType
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
                OutputStream os = conn.getOutputStream();
                DataOutputStream ds = new DataOutputStream(os);
                NetUtil.writeStringParams(textParams, ds);
                NetUtil.writeFileParams(fileparams, ds);
                NetUtil.paramsEnd(ds);
                // 对文件流操作完,要记得及时关闭
                os.close();
                // 服务器返回的响应吗
                int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
                // 对响应码进行判断
                if (code == 200) {// 返回的响应码200,是成功
                    // 得到网络返回的输入流
                    InputStream is = conn.getInputStream();
                    resultStr = NetUtil.readString(is);
                    System.out.println(resultStr);
                    JSONObject jsonObject = new JSONObject(resultStr);
//                    JSONObject resultJson = jsonObject.getJSONObject(resultStr);
                    System.out.println("resultJson = = = = = =  = = " + jsonObject);
                    
                } else {
                    Toast.makeText(mContext, "请求URL失败！", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
        }
    };
    
    Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                pd.dismiss();

                try {
                    JSONObject jsonObject = new JSONObject(resultStr);
                    if (jsonObject.optString("status").equals("100")) {
                        BitmapFactory.Options option = new BitmapFactory.Options();
                        option.inSampleSize = 1;

                        String imageUrl = jsonObject.optString("message");
                        FlyAntGlobalVar.upic = imageUrl;
                        sp.edit().putString("upic", imageUrl).commit();
                        Toast.makeText(mContext, "头像上传成功", Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        Toast.makeText(mContext,
                                jsonObject.optString("message"),
                                Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;

            default:
                break;
            }
            return false;
        }
    });
    
    
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
        
    };
    

    private void refresh() {
        sp = getActivity().getSharedPreferences("filename", Context.MODE_PRIVATE);
        FlyAntGlobalVar.upic = sp.getString("upic", "");
        FlyAntGlobalVar.uid = sp.getString("uid", "");
        String uid = sp.getString("uid", "");
        new NetWorkTask().execute(uid);
//        Log.i(TAG, "upic ======"+ userinfo);
        
        new Thread(new Runnable() {
            

            @Override
            public void run() {
                final Bitmap bitmap = returnBitMap(FlyAntGlobalVar.upic);
                iv_user_head_portrait.post(new Runnable() {

                    @Override
                    public void run() {
                        iv_user_head_portrait.setImageBitmap(bitmap);
                        
                    }
                });
            }

            protected Bitmap returnBitMap(String url) {
                URL myFileUrl = null;
                Bitmap bitmap = null;
                try {
                    myFileUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setRequestMethod("GET");
                    if(conn.getResponseCode() == 200){
                    InputStream inputStream = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    FileUtil.saveFile(mContext, IMAGE_FILE_NAME, bitmap);
                    inputStream.close();
                    }
                } catch (Exception e) {
                    Log.i(TAG, e.getMessage());
                    e.printStackTrace();
                }
                return bitmap;
            }
        }).start();
    }
    private String urlpath;    
    class NetWorkTask extends AsyncTask<String, Integer, User>
    {
        ProgressDialog dialog = new ProgressDialog(getActivity());
//        ProgressDialog progressDialog = ProgressDialogUtil.dialogByDoing(UserFragment.this);

        @Override
        protected void onPreExecute()
        {
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected User doInBackground(String... params)
        {
            UserService uService = new UserService();
            return uService.queryUserInfo(params[0]);
        }

        @Override
        protected void onPostExecute(final User user) 
        {
            dialog.dismiss();
            if( null == user ) 
            {
//                showErrorDialog(getActivity().this,"网络连接失败,请稍后再试").show();
//              SalesmanDetailActivity.this.finish();
            }
            else if( !"".equals(user.getUid())&&user.getUid() != null ) 
            {       
//                iv_user_head_portrait.setImageBitmap(returnBitMap(FlyAntGlobalVar.upic));
                tv_user_name.setText(user.getName());
                tv_user_nickname.setText(user.getNickname());
                tv_user_phonenum.setText(user.getSendTel());
                tv_user_goodsaddress.setText(user.getSendAddress());
                tv_user_address.setText(user.getAddress());
//                FlyAntGlobalVar.upic = user.getUpic();
                
            }
            else 
            {
                // 获取错误码
                Toast.makeText(getActivity(), user.getRetCode(), Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(user);
        }    
        
    }
    
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            refresh();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(((MainActivity)getActivity()).isConflict){
            outState.putBoolean("isConflict", true);
        }else if(((MainActivity)getActivity()).getCurrentAccountRemoved()){
            outState.putBoolean(Constant.ACCOUNT_REMOVED, true);
        }
    }

}
